<template>
  <div class="my-goods-list">
    <MyTable :list="list">
      <template #head>
        <th>#</th>
        <th>商品名称</th>
        <th>价格</th>
        <th>标签</th>
        <th>操作</th>
      </template>

      <template #body="scoped">
        <td>{{ scoped.obj.id }}</td>
        <td>{{ scoped.obj.goods_name }}</td>
        <td>{{ scoped.obj.goods_price }}</td>
        <td>
          <div>
            <!-- 输入框 -->
            <input
              v-focus
              style="width: 150px"
              class="tag-input form-control"
              type="text"
              v-model.trim="scoped.obj.inputValue"
              v-if="scoped.obj.inputVisible"
              @blur="scoped.obj.inputVisible = false"
              @keyup.esc="scoped.obj.inputValue = ''"
              @keyup.enter="addFn(scoped.obj)"
            />
            <button
              v-else
              @click="scoped.obj.inputVisible = true"
              class="btn btn-primary btn-sm add-tag"
            >
              +Tag
            </button>
          </div>
          <span
            v-for="(item, index) in scoped.obj.tags"
            :key="index"
            class="badge rounded-pill bg-warning text-dark"
          >
            {{ item }}</span
          >
        </td>
        <td>
          <button class="btn btn-danger btn-sm" @click="delFn(scoped.obj.id)">
            删除
          </button>
        </td>
      </template>
    </MyTable>
  </div>
</template>

<script>
import axios from "axios";
// 接口：GTE  https://www.escook.cn/api/goods
import MyTable from "../components/MyTable.vue";
export default {
  data() {
    return {
      list: [],
    };
  },

  async created() {
    const { data: res } = await axios.get("https://www.escook.cn/api/goods");
    // console.log(res);
    this.list = res.data;
  },

  components: {
    MyTable,
  },
  // 自定义指令
  directives: {
    focus: {
      inserted(el) {
        el.focus();
      },
    },
  },
  methods: {
    // 删除
    delFn(id) {
      // console.log(id);
      this.list = this.list.filter((item) => item.id !== id);
    },
    // 添加标签
    addFn(obj) {
      // console.log(obj);
      if (obj.inputValue.length === 0) {
        return alert("请输入信息");
      }
      obj.tags.push(obj.inputValue);
      obj.inputValue = "";
    },
  },
};
</script>

<style>
</style>
